package cn.majingjing.core.shell;

import cn.majingjing.core.tool.Tools;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;

/**
 * @author majinding888@foxmail.com
 */
public class ShellTools {

	private static Logger log = LoggerFactory.getLogger(ShellTools.class);

	public static String exec(String shpath, String... args) throws Exception {
		CommandLine cmdLine = new CommandLine("bash");
		cmdLine.addArgument(shpath);
		for (String arg : args) {
			cmdLine.addArgument(arg);
		}
		return executeShell(cmdLine);
	}

	public static String executeShell(CommandLine commandLine) throws Exception {
		ByteArrayOutputStream outputStream = null;
		try {
			log.debug("执行脚本命令:{}", commandLine.toString().replaceAll(",", ""));
			if(!Tools.isLinuxOS()){
				throw new Exception(Tools.toStrings("此操作系统[{}]不支持shell脚本命令",System.getProperty("os.name")));
			}
			outputStream = new ByteArrayOutputStream();
			ExecuteWatchdog watchdog = new ExecuteWatchdog(3 * 60 * 1000);
			PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
			DefaultExecutor executor = new DefaultExecutor();
			executor.setExitValue(0);
			executor.setWatchdog(watchdog);
			executor.setStreamHandler(streamHandler);
			int temp = executor.execute(commandLine);
			if (executor.isFailure(temp)) {
				// it was killed on purpose by the watchdog
				watchdog.killedProcess();
			}
			byte[] buf = outputStream.toByteArray();
			String result = new String(buf);
			log.debug("控制台输出:{}", result);
			return result;
		} finally {
			if (outputStream != null)
				outputStream.close();
		}
	}

}
